<script setup lang="ts">
import { requestUpload } from "@/utils/request";
import Taro from "@tarojs/taro";
import { twMerge } from "tailwind-merge";
import ByIcon from "../ui/ByIcon.vue";
import { suffixUnit } from "@/utils";
import ApiApp from "@/api/app";

const {
  showThum = true,
  count = 1,
  size = 180,
} = defineProps<{
  count?: number;
  showThum?: boolean;
  avatar?: boolean;
  mode?: "list" | "card";

  /**
   * 尺寸大小
   */
  size?: number | string;

  /**
   * 是否禁用
   */
  disabled?: boolean;
}>();

/**单
 * 文件资源地址
 */
const model = defineModel<string>();

/**
 * 图片列表
 */
const list = defineModel<{ url: string; }[]>("list");

const choose = async () => {
  const { tempFiles } = await Taro.chooseMedia({
    count,
    mediaType: ["image"],
    sizeType: ["compressed", "original"],
  });

  await upload(tempFiles[0].tempFilePath);
};

const chooseavatar = (e) => upload(e.detail.avatarUrl);

const upload = (filePath) => {
  Taro.showLoading();
  requestUpload(ApiApp.uploadFile, filePath).then(({ urls }) => {
    model.value = urls;
    Taro.showToast({ title: "上传成功" });
  });
};

console.log("model",model);

</script>

<template>
  <view
        :class="twMerge('relative inline-block rounded-md overflow-hidden bg-black/10', $attrs.class as string)"
        @tap="!disabled && !avatar && choose()"
        :style="`width:${suffixUnit(size)}; height: ${suffixUnit(size)}`">
    <slot>
      <image v-if="showThum && model" class="w-full h-full" :src="model" />
      <view v-else class="flex-center w-full h-full">
        <ByIcon name="Plus" color="#999" :size="36" />
      </view>
    </slot>

    <button
            v-if="avatar"
            class="absolute top-0 left-0 !w-full h-full opacity-0"
            open-type="chooseAvatar"
            :disabled="disabled"
            @chooseavatar="chooseavatar" />
  </view>
</template>
